package handler

import (
	"context"
	"strconv"
	"time"

	"github.com/gin-gonic/gin"
	"go.uber.org/zap"

	"yanxue_ai_go/pkg/common/logger"
	"yanxue_ai_go/pkg/common/response"
	"yanxue_ai_go/services/agent/internal/service"
)

// KnowledgeHandler 知识百科处理器
type KnowledgeHandler struct {
	knowledgeService *service.KnowledgeAgentService
}

// NewKnowledgeHandler 创建知识百科处理器
func NewKnowledgeHandler(aiService *service.AIService) *KnowledgeHandler {
	knowledgeService := service.NewKnowledgeAgentService(aiService)
	return &KnowledgeHandler{
		knowledgeService: knowledgeService,
	}
}

// CreateKnowledgeAgent 创建知识百科Agent
func (h *KnowledgeHandler) CreateKnowledgeAgent(c *gin.Context) {
	var req service.CreateKnowledgeAgentRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		response.BadRequest(c, err.Error())
		return
	}

	// 设置默认值
	if req.Model == "" {
		req.Model = "gpt-3.5-turbo"
	}
	if req.Temperature == 0 {
		req.Temperature = 0.7
	}
	if req.MaxTokens == 0 {
		req.MaxTokens = 2000
	}
	if req.ResponseStyle == "" {
		req.ResponseStyle = "detailed"
	}
	if req.Difficulty == "" {
		req.Difficulty = "medium"
	}
	if req.MaxQuestions == 0 {
		req.MaxQuestions = 100
	}
	if len(req.Categories) == 0 {
		req.Categories = []string{"综合知识"}
	}
	if len(req.Languages) == 0 {
		req.Languages = []string{"中文"}
	}

	agent, err := h.knowledgeService.CreateKnowledgeAgent(c.Request.Context(), &req)
	if err != nil {
		logger.Logger.Error("Failed to create knowledge agent", zap.Error(err))
		response.InternalServerError(c, "Failed to create knowledge agent")
		return
	}

	response.Success(c, agent)
}

// StartKnowledgeSession 开始知识问答会话
func (h *KnowledgeHandler) StartKnowledgeSession(c *gin.Context) {
	var req service.StartKnowledgeSessionRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		response.BadRequest(c, err.Error())
		return
	}

	session, err := h.knowledgeService.StartKnowledgeSession(c.Request.Context(), &req)
	if err != nil {
		logger.Logger.Error("Failed to start knowledge session", zap.Error(err))
		response.InternalServerError(c, "Failed to start knowledge session")
		return
	}

	response.Success(c, gin.H{
		"session_id": session.SessionID,
		"started_at": session.StartedAt,
		"message":    "知识问答会话已开始，您可以开始提问了！",
	})
}

// AskQuestion 向知识百科Agent提问
func (h *KnowledgeHandler) AskQuestion(c *gin.Context) {
	var req service.AskQuestionRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		response.BadRequest(c, err.Error())
		return
	}

	// 设置默认语言
	if req.Language == "" {
		req.Language = "中文"
	}

	ctx, cancel := context.WithTimeout(c.Request.Context(), 60*time.Second)
	defer cancel()

	answer, err := h.knowledgeService.AskQuestion(ctx, &req)
	if err != nil {
		logger.Logger.Error("Failed to answer question",
			zap.Error(err),
			zap.String("question", req.Question))
		response.InternalServerError(c, "Failed to get answer")
		return
	}

	response.Success(c, answer)
}

// GetKnowledgeHistory 获取知识问答历史
func (h *KnowledgeHandler) GetKnowledgeHistory(c *gin.Context) {
	var req service.GetKnowledgeHistoryRequest
	if err := c.ShouldBindQuery(&req); err != nil {
		response.BadRequest(c, err.Error())
		return
	}

	// 设置默认值
	if req.Page == 0 {
		req.Page = 1
	}
	if req.PageSize == 0 {
		req.PageSize = 20
	}

	history, err := h.knowledgeService.GetKnowledgeHistory(c.Request.Context(), &req)
	if err != nil {
		logger.Logger.Error("Failed to get knowledge history", zap.Error(err))
		response.InternalServerError(c, "Failed to get knowledge history")
		return
	}

	response.Success(c, history)
}

// RateAnswer 对答案进行评分
func (h *KnowledgeHandler) RateAnswer(c *gin.Context) {
	var req service.RateAnswerRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		response.BadRequest(c, err.Error())
		return
	}

	if err := h.knowledgeService.RateAnswer(c.Request.Context(), &req); err != nil {
		logger.Logger.Error("Failed to rate answer", zap.Error(err))
		response.InternalServerError(c, "Failed to rate answer")
		return
	}

	response.Success(c, gin.H{"message": "评分提交成功，感谢您的反馈！"})
}

// GetKnowledgeAnalytics 获取知识百科分析数据
func (h *KnowledgeHandler) GetKnowledgeAnalytics(c *gin.Context) {
	agentIDStr := c.Param("id")
	agentID, err := strconv.ParseUint(agentIDStr, 10, 32)
	if err != nil {
		response.BadRequest(c, "Invalid agent ID")
		return
	}

	daysStr := c.DefaultQuery("days", "7")
	days, err := strconv.Atoi(daysStr)
	if err != nil || days < 1 || days > 365 {
		days = 7
	}

	analytics, err := h.knowledgeService.GetKnowledgeAnalytics(c.Request.Context(), uint(agentID), days)
	if err != nil {
		logger.Logger.Error("Failed to get knowledge analytics", zap.Error(err))
		response.InternalServerError(c, "Failed to get analytics")
		return
	}

	response.Success(c, analytics)
}

// QuickAsk 快速提问（无需会话）
func (h *KnowledgeHandler) QuickAsk(c *gin.Context) {
	agentIDStr := c.Param("id")
	agentID, err := strconv.ParseUint(agentIDStr, 10, 32)
	if err != nil {
		response.BadRequest(c, "Invalid agent ID")
		return
	}

	var reqBody struct {
		Question string `json:"question" binding:"required"`
		Language string `json:"language"`
	}

	if err := c.ShouldBindJSON(&reqBody); err != nil {
		response.BadRequest(c, err.Error())
		return
	}

	req := service.AskQuestionRequest{
		AgentID:  uint(agentID),
		Question: reqBody.Question,
		Language: reqBody.Language,
	}

	if req.Language == "" {
		req.Language = "中文"
	}

	ctx, cancel := context.WithTimeout(c.Request.Context(), 60*time.Second)
	defer cancel()

	answer, err := h.knowledgeService.AskQuestion(ctx, &req)
	if err != nil {
		logger.Logger.Error("Failed to answer quick question",
			zap.Error(err),
			zap.String("question", req.Question))
		response.InternalServerError(c, "Failed to get answer")
		return
	}

	response.Success(c, gin.H{
		"question":       req.Question,
		"answer":         answer.Answer,
		"category":       answer.Category,
		"confidence":     answer.Confidence,
		"response_time":  answer.ResponseTime,
		"suggestions":    answer.Suggestions,
		"related_topics": answer.RelatedTopics,
	})
}

// GetKnowledgeAgentInfo 获取知识Agent信息
func (h *KnowledgeHandler) GetKnowledgeAgentInfo(c *gin.Context) {
	agentIDStr := c.Param("id")
	agentID, err := strconv.ParseUint(agentIDStr, 10, 32)
	if err != nil {
		response.BadRequest(c, "Invalid agent ID")
		return
	}

	// 这里应该调用service获取Agent详细信息
	// 为了简化，返回基本信息
	response.Success(c, gin.H{
		"id":      agentID,
		"message": "Knowledge agent info endpoint",
		"endpoints": gin.H{
			"quick_ask":     "/api/v1/knowledge/" + agentIDStr + "/ask",
			"start_session": "/api/v1/knowledge/" + agentIDStr + "/session",
			"analytics":     "/api/v1/knowledge/" + agentIDStr + "/analytics",
		},
	})
}

// GetKnowledgeCategories 获取知识分类
func (h *KnowledgeHandler) GetKnowledgeCategories(c *gin.Context) {
	// 返回预定义的知识分类
	categories := []gin.H{
		{"id": 1, "name": "科学技术", "name_en": "science_technology", "icon": "🔬", "color": "#3498db"},
		{"id": 2, "name": "历史人文", "name_en": "history_culture", "icon": "📚", "color": "#e74c3c"},
		{"id": 3, "name": "地理自然", "name_en": "geography_nature", "icon": "🌍", "color": "#27ae60"},
		{"id": 4, "name": "医学健康", "name_en": "medical_health", "icon": "🏥", "color": "#e67e22"},
		{"id": 5, "name": "经济商业", "name_en": "economy_business", "icon": "💼", "color": "#9b59b6"},
		{"id": 6, "name": "教育学习", "name_en": "education_learning", "icon": "🎓", "color": "#f39c12"},
		{"id": 7, "name": "生活常识", "name_en": "daily_life", "icon": "🏠", "color": "#1abc9c"},
		{"id": 8, "name": "综合知识", "name_en": "general_knowledge", "icon": "🧠", "color": "#34495e"},
	}

	response.Success(c, gin.H{
		"categories": categories,
		"total":      len(categories),
	})
}

// GetPopularQuestions 获取热门问题
func (h *KnowledgeHandler) GetPopularQuestions(c *gin.Context) {
	agentIDStr := c.Param("id")
	agentID, err := strconv.ParseUint(agentIDStr, 10, 32)
	if err != nil {
		response.BadRequest(c, "Invalid agent ID")
		return
	}

	category := c.Query("category")
	limit := c.DefaultQuery("limit", "10")

	// 这里应该从数据库查询热门问题
	// 为了演示，返回模拟数据
	popularQuestions := []gin.H{
		{"question": "什么是人工智能？", "category": "科学技术", "ask_count": 156},
		{"question": "地球有多少年历史？", "category": "地理自然", "ask_count": 134},
		{"question": "如何保持健康的生活方式？", "category": "医学健康", "ask_count": 128},
		{"question": "什么是区块链技术？", "category": "科学技术", "ask_count": 112},
		{"question": "中国有多少个省份？", "category": "地理自然", "ask_count": 98},
	}

	response.Success(c, gin.H{
		"agent_id":  agentID,
		"category":  category,
		"limit":     limit,
		"questions": popularQuestions,
	})
}
